<template>
  <div class="post-management">
    <div class="page-header">
      <h2>帖子管理</h2>
      <div>
        <el-button type="primary" @click="goToUserPostPage">
          <el-icon><Upload /></el-icon>上传帖子
        </el-button>
        <el-button type="danger" :disabled="!selectedPosts.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子标题或内容"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="filters.status" placeholder="状态" clearable>
       <el-option label="待审核" value="pending" />
       <el-option label="已通过" value="approved" />
       <el-option label="已拒绝" value="rejected" />
      </el-select>
      <el-date-picker
        v-model="filters.dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 帖子列表 -->
    <el-table
      v-loading="loading"
      :data="posts"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="previewPost(row)">{{ row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="author.username" label="作者" width="120" />
      <el-table-column prop="category" label="分类" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="views" label="浏览" width="100" />
      <el-table-column prop="likes" label="点赞" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
           <template v-if="row.status === 'pending'">
             <el-button size="small" type="success" @click="handleApprovePost(row)">通过</el-button>
             <el-button size="small" type="warning" @click="handleRejectPost(row)">拒绝</el-button>
           </template>
            <el-button size="small" @click="previewPost(row)">预览</el-button>
        
            <el-button
              size="small"
              type="danger"
              @click="deletePost(row)"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="帖子预览"
      width="60%"
      destroy-on-close
    >
      <div v-if="selectedPost" class="post-preview">
        <h3>{{ selectedPost.title }}</h3>
        <div class="post-meta">
          <span>作者：{{ selectedPost.author.username }}</span>
          <span>发布时间：{{ formatDate(selectedPost.createdAt) }}</span>
          <span>分类：{{ selectedPost.category.name }}</span>
        </div>
        <div class="post-content" v-html="selectedPost.content" />
      </div>
    </el-dialog>

    <!-- 上传帖子对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传帖子"
      width="60%"
      @close="resetUploadForm"
    >
      <el-form
        ref="postFormRef"
        :model="postForm"
        :rules="postRules"
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题（2-100个字符）" 
            maxlength="100" 
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入帖子内容（至少10个字符）" 
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="话题" prop="tags"> 
          <el-select
            v-model="postForm.tags" 
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="选择或创建话题（最多5个）"
            :max-collapse-tags="3"
          >
            <el-option
              v-for="topic in hotTopics"
              :key="topic"
              :label="topic"
              :value="topic"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="postForm.category" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category._id"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="图片">
          <el-upload
            v-model:file-list="fileList" 
            class="post-uploader"
            action="#" 
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :limit="9"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">支持 JPG/PNG 等图片格式，单张不超过 5MB，最多上传9张</div> 
            </template>
          </el-upload>
        </el-form-item>
        
        <div class="form-actions">
          <el-button @click="saveDraft" :loading="isSavingDraft">保存草稿</el-button> 
          <el-button type="primary" @click="submitPost" :loading="isSubmitting">
            发布
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Upload, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/services/axios.js' // 导入配置好的 axios 实例

// 状态变量
const loading = ref(false)
const posts = ref([])
const selectedPosts = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const filters = reactive({
  status: '',
  dateRange: null
})
const hotTopics = ref([])
const categories = ref([])

// 获取帖子分类
const fetchCategories = async () => {
  try {
    const response = await http.get('/api/categories')
    categories.value = response.data
    console.log('获取到的分类数据:', categories.value)
    if (!categories.value || categories.value.length === 0) {
      // 如果没有获取到分类数据，使用默认分类
      categories.value = [
        { _id: '1', name: '音乐', path: 'music' },
        { _id: '2', name: '游戏', path: 'gaming' },
        { _id: '3', name: '教育', path: 'education' },
        { _id: '4', name: '科技', path: 'tech' },
        { _id: '5', name: '生活', path: 'lifestyle' },
        { _id: '6', name: '电影', path: 'movies' },
        { _id: '7', name: '动漫', path: 'anime' },
        { _id: '8', name: '体育', path: 'sports' },
        { _id: '9', name: '搞笑', path: 'comedy' },
        { _id: '10', name: '其他', path: 'other' }
      ]
      console.log('使用默认分类数据:', categories.value)
    }
  } catch (error) {
    console.error('获取帖子分类失败:', error)
    ElMessage.error('获取帖子分类失败')
    // 使用默认分类数据
    categories.value = [
      { _id: '1', name: '音乐', path: 'music' },
      { _id: '2', name: '游戏', path: 'gaming' },
      { _id: '3', name: '教育', path: 'education' },
      { _id: '4', name: '科技', path: 'tech' },
      { _id: '5', name: '生活', path: 'lifestyle' },
      { _id: '6', name: '电影', path: 'movies' },
      { _id: '7', name: '动漫', path: 'anime' },
      { _id: '8', name: '体育', path: 'sports' },
      { _id: '9', name: '搞笑', path: 'comedy' },
      { _id: '10', name: '其他', path: 'other' }
    ]
    console.log('使用默认分类数据:', categories.value)
  }
}

// 预览相关
const previewDialogVisible = ref(false)
const selectedPost = ref(null)

// 上传帖子相关
const showUploadDialog = ref(false)
const postFormRef = ref(null)
const isSubmitting = ref(false)
const isSavingDraft = ref(false)
const fileList = ref([])

// 表单数据
const postForm = reactive({
  title: '',
  content: '',
  tags: [],
  category: '',
})

// 表单验证规则
const postRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容至少10个字符', trigger: 'blur' }
  ],
  tags: [
    { type: 'array', max: 5, message: '最多选择5个话题', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 获取帖子列表
const fetchPosts = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value, // 修改参数名为 search
      status: filters.status,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    }
     
   // 管理员获取帖子列表，后端 getPosts 已处理
   const response = await http.get('/api/posts', { params }) // 使用 /api/posts，后端根据角色过滤
    posts.value = response.data.posts
    total.value = response.data.totalPosts // 确保使用正确的 total 字段
  } catch (error) {
    console.error('获取帖子列表失败：', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 获取热门话题
const fetchHotTopics = async () => {
  try {
    const response = await http.get('/api/topics/hot')
    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
      hotTopics.value = response.data
      console.log('获取到的热门话题:', hotTopics.value)
    } else {
      console.warn('热门话题接口返回数据格式不正确或为空，将使用前端预设。')
      // 使用默认热门话题
      hotTopics.value = [
        '生活', '美食', '旅行', '电影', '音乐',
        '游戏', '动漫', '科技', '运动', '宠物'
      ]
      console.log('使用默认热门话题:', hotTopics.value)
    }
  } catch (error) {
    console.error('获取热门话题失败:', error)
    // 使用默认热门话题
    hotTopics.value = [
      '生活', '美食', '旅行', '电影', '音乐',
      '游戏', '动漫', '科技', '运动', '宠物'
    ]
    console.log('获取失败，使用默认热门话题:', hotTopics.value)
  }
}

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1 
  fetchPosts()
}

const resetFilters = () => {
  searchQuery.value = ''
  filters.status = ''
  filters.dateRange = null
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPosts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPosts()
}

// 表格选择
const handleSelectionChange = (val) => {
  selectedPosts.value = val
}

// 预览帖子
const previewPost = (post) => {
  selectedPost.value = post
  previewDialogVisible.value = true
}

// 获取状态类型
const getStatusType = (status) => {
 const typeMap = {
   pending: 'info',
   approved: 'success',
   rejected: 'danger',
   // hidden: 'warning' // 如果保留隐藏功能
 }
 return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
 const textMap = {
   pending: '待审核',
   approved: '已通过',
   rejected: '已拒绝',
   // hidden: '已隐藏'
 }
 return textMap[status] || '未知'
}

// 审核通过帖子
const handleApprovePost = async (post) => {
 try {
   await http.put(`/api/admin/posts/${post._id}/status`, { status: 'approved' }) // 修改为 PUT
   ElMessage.success('帖子已通过审核')
   post.status = 'approved'
 } catch (error) {
   console.error('审核通过帖子失败:', error)
   ElMessage.error('操作失败')
 }
}

// 拒绝帖子
const handleRejectPost = async (post) => {
 try {
   const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因（可选）', '拒绝帖子', {
     confirmButtonText: '确定拒绝',
     cancelButtonText: '取消',
     inputPattern: /.*/,
     inputErrorMessage: '',
   })

   await http.put(`/api/admin/posts/${post._id}/status`, { status: 'rejected', reason }) // 修改为 PUT
   ElMessage.success('帖子已拒绝')
   post.status = 'rejected'
 } catch (error) {
   if (error !== 'cancel') {
     console.error('拒绝帖子失败:', error)
     ElMessage.error('操作失败')
   }
 }
}

// 删除帖子
const deletePost = async (post) => {
  try {
    await ElMessageBox.confirm(`确定要删除帖子 "${post.title}" 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await http.delete(`/api/posts/${post._id}`)
    ElMessage.success('删除成功')
    // 从列表中移除
    const index = posts.value.findIndex(p => p._id === post._id)
    if (index !== -1) {
      posts.value.splice(index, 1)
      total.value -= 1
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除帖子失败：', error)
      ElMessage.error('删除帖子失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedPosts.value.length} 个帖子吗？此操作不可恢复`)
    const postIds = selectedPosts.value.map(post => post._id)
    await http.delete('/api/admin/posts', { data: { postIds } }) // 修改为 DELETE /api/admin/posts，并在 data 中传递 postIds
    ElMessage.success('批量删除成功')
    fetchPosts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败：', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理图片文件变化
const handleImageChange = (file, files) => {
  fileList.value = files.map(f => ({ ...f, raw: f.raw || file.raw }))
}

// 处理图片文件移除
const handleImageRemove = (file, files) => {
  fileList.value = files
}

// 发布帖子
const submitPost = async () => {
  if (!postFormRef.value) return

  await postFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      
      try {
        const formData = new FormData()
        formData.append('title', postForm.title)
        formData.append('content', postForm.content)
        postForm.tags.forEach(tag => formData.append('tags[]', tag))
    formData.append('category', postForm.category)
    formData.append('isDraft', false) // 修改为布尔值 false
        
        // 添加图片文件
        fileList.value.forEach(file => {
          if (file.raw) {
            formData.append('images', file.raw)
          }
        })
        
        const response = await http.post('/api/admin/posts', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        ElMessage.success('帖子发布成功')
        showUploadDialog.value = false
        resetUploadForm()
        fetchPosts()
      } catch (error) {
        console.error('发布失败:', error)
        ElMessage.error(error.response?.data?.error || '发布失败，请稍后重试')
      } finally {
        isSubmitting.value = false
      }
    } else {
      ElMessage.error('请检查表单信息是否完整')
    }
  })
}

// 保存草稿
const saveDraft = async () => {
  if (!postFormRef.value) return

  await postFormRef.value.validateField('title', async (isValid) => {
    if (isValid) {
      isSavingDraft.value = true
      try {
        const formData = new FormData()
        formData.append('title', postForm.title)
        formData.append('content', postForm.content)
        postForm.tags.forEach(tag => formData.append('tags[]', tag))
    formData.append('category', postForm.category)
    formData.append('isDraft', true) // 保存草稿时为 true

        // 添加图片文件
        fileList.value.forEach(file => {
          if (file.raw) {
            formData.append('images', file.raw)
          }
        })

        await http.post('/api/admin/posts', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        ElMessage.success('草稿保存成功')
        showUploadDialog.value = false
        resetUploadForm()
        fetchPosts()
      } catch (error) {
        console.error('保存草稿失败:', error)
        ElMessage.error(error.response?.data?.error || '保存草稿失败，请稍后重试')
      } finally {
        isSavingDraft.value = false
      }
    }
  })
}

// 重置上传表单
const resetUploadForm = () => {
  postFormRef.value.resetFields()
  fileList.value = []
  postForm.title = ''
  postForm.content = ''
  postForm.tags = []
  postForm.category = ''
}

// 跳转到用户发布帖子页面
import { useRouter } from 'vue-router'
const router = useRouter()
const goToUserPostPage = () => {
  router.push('/post') 
}

// 初始化
onMounted(() => {
   fetchPosts()
   fetchHotTopics()
   fetchCategories()
 })

</script>

<style scoped>
.post-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.post-preview {
  .post-meta {
    display: flex;
    gap: 20px;
    color: #666;
    margin: 10px 0 20px;
  }

  .post-content {
    line-height: 1.6;
  }
}
</style>